package suanfa.search;

public class BinarySearch {

    public static void main(String[] args) {
        int[] arr=new int[1000];
    int[] arr2={2,3,7,9,12,24,656};
        for (int i = 0; i < 1000; i++) {
            arr[i]=i;
        }
        int index=binarySearch(arr,173);
        int index2=binarySearch(arr2,3);

        System.out.println(index);

        System.out.println(index2);
    }

    public static int binarySearch(int[] arr,int target){
        //查找范围起点
        int start=0;
        //查找范围终点
        int end=arr.length-1;
        //查找范围的中位数
        int mid;


        while(start<end){
            //mid=(start+end)/2又可能溢出，如果数组元素的数量接近于整型数的最大值，那么start与end的下标之和，就有可能超出整型范围，造成溢出
            mid=start+((end-start)/2)+1;
            if(arr[mid]==target){
                return mid;
            }else if(arr[mid]>target){
                end=mid-1;
            }else{
                start=mid+1;
            }
        }

        return -1;
    }
}
